package www.openteam.com.ui.business;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.util.SortedList;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.util.ArrayList;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.CustomAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.CustomConditon;
import www.openteam.com.bean.CustomType;
import www.openteam.com.bean.InsertStatus;
import www.openteam.com.bean.QueryCustom;
import www.openteam.com.contract.business.EditCustomInfoContract;
import www.openteam.com.presenter.business.EditCustomInfoPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * 查询客户信息
 * Created by hyd on 2016/10/16.
 */

public class QueryCustomInfoFragment extends mBaseFragment<EditCustomInfoPresenter>
        implements EditCustomInfoContract.QueryCustomInfoView {

    private ArrayList<QueryCustom.DataBean> editCustomInfos;
    private ArrayList<QueryCustom.DataBean> editCustoms;
    private ArrayList<CustomType.DataBean> customTypes = new ArrayList<CustomType.DataBean>();
    private ArrayList<CustomType.DataBean> moneyTypes = new ArrayList<CustomType.DataBean>();
    private ArrayList<CustomType.DataBean> copayTypes = new ArrayList<CustomType.DataBean>();
    private static int pageSize = 0;
    private final String TAG = "PurchaseOrderAppro";
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private CustomAdapter editCustomInfoAdapter = null;
    Throwable throwable = null;
    FragmentManager fm;
    private ButtonInterface buttonInterface;

    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;
    @Bind(R.id.ed_5)
    EditText ed_3;
    @Bind(R.id.query_btn)
    Button query_btn;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        fm = getActivity().getSupportFragmentManager();

    }


    //设置适配器
    private void setEditCustomInfoAdapter() {
        if (editCustomInfoAdapter == null) {
            editCustomInfoAdapter = new CustomAdapter(getActivity());
            editCustomInfoAdapter.addItems(editCustomInfos);
            editCustomInfoAdapter.addItemM(customTypes, moneyTypes, copayTypes, getContext());
            editCustomInfoAdapter.buttonSetOnclick(new CustomAdapter.ButtonInterface() {

                @Override
                public void onclick(View view, int position, ArrayList<CustomConditon> customConditons, ArrayList<CustomType.DataBean> customTypes, ArrayList<CustomType.DataBean> moneyTypes, ArrayList<CustomType.DataBean> copayTypes) {
                    buttonInterface.onclick(view, position,
                                    editCustoms.get(position), customConditons,
                                    customTypes, moneyTypes, copayTypes);

                }

                @Override
                public void modify(View view, int position, ArrayList<CustomConditon> customConditons,
                                   ArrayList<CustomType.DataBean> customTypes,
                                   ArrayList<CustomType.DataBean> moneyTypes,
                                   ArrayList<CustomType.DataBean> copayTypes,
                                   SortedList<QueryCustom.DataBean> mSortedList) {
//                    createProgressDialog(getString(R.string.modifing));
                    buttonInterface.modify(view, position,
                            editCustoms.get(position), customConditons,
                            customTypes, moneyTypes, copayTypes, mSortedList);
                }

                @Override
                public void delete(int id) {
                    createProgressDialog(getString(R.string.deleting));
                    mPresenter.deleteCustomInfo(id);
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(editCustomInfoAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            editCustomInfoAdapter.addItems(editCustomInfos);
//            editCustomInfoAdapter.addItemM(customTypes,moneyTypes,copayTypes,getContext());
            editCustomInfoAdapter.buttonSetOnclick(new CustomAdapter.ButtonInterface() {

                @Override
                public void onclick(View view, int position, ArrayList<CustomConditon> customConditons,
                                    ArrayList<CustomType.DataBean> customTypes, ArrayList<CustomType.DataBean> moneyTypes,
                                    ArrayList<CustomType.DataBean> copayTypes) {
                    buttonInterface.onclick(view, position, editCustoms.get(position), customConditons,
                            customTypes, moneyTypes, copayTypes);
                }

                @Override
                public void modify(View view, int position, ArrayList<CustomConditon>
                        customConditons, ArrayList<CustomType.DataBean> customTypes,
                                   ArrayList<CustomType.DataBean> moneyTypes,
                                   ArrayList<CustomType.DataBean> copayTypes,
                                   SortedList<QueryCustom.DataBean> mSortedList) {
//                    createProgressDialog(getString(R.string.modifing));
                    buttonInterface.modify(view, position, editCustoms.get(position),
                            customConditons, customTypes, moneyTypes,
                            copayTypes, mSortedList);
                }

                @Override
                public void delete(int id) {
                    createProgressDialog(getString(R.string.deleting));
                    mPresenter.deleteCustomInfo(id);
                }
            });
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }


    //创建ProgressDialog    mBaseFragment 里面有, 舍弃
//    private void createProgressDialog(){
//        mContext=getContext();
//
//        mProgressDialog = new ProgressDialog(mContext);
//        mProgressDialog.setMessage("...请您稍等...");
//        mProgressDialog.show();
//    }

    //下拉刷新
    @Override
    public void onRefresh() {
        //如果view内ChildCount>0
        if ((mRecyclerView.getChildCount() > 0) &&
                (!getCode().isEmpty() || !getName().isEmpty()) || !getBusinessman().isEmpty()) {
//            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            editCustomInfos.clear();
            editCustomInfoAdapter = null;
            editCustoms.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(),0);
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) &&
                (!getCode().isEmpty() || !getName().isEmpty())) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            editCustomInfoAdapter = null;
            editCustomInfos.clear();
            editCustoms.clear();
            i = 0;
            mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), 0);
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() >= 0) && (mRecyclerView != null) && (mSwipeRefresh != null)) {

            mRecyclerView.removeAllViews();
            editCustomInfoAdapter = null;
            editCustomInfos.clear();
            editCustoms.clear();
            i = 0;
            mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }

    // 隐藏状态改变
    @Override
    public void onHiddenChanged(boolean hidden) {
        String code = ((DetailedActivity) getActivity()).getQueryCode();
        if (hidden == false && code != null) {
            Log.d(TAG, "onHiddenChanged: " + code);
            mRecyclerView.removeAllViews();
            editCustomInfos.clear();
            editCustomInfoAdapter = null;
            editCustoms.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryCocustomInfos(getCode(), "", "",getUserID(),0);
//            mPresenter.queryCocustomInfo(code, "", "", 0);
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (editCustomInfos.size() % 10 == 0)) {

                Log.d(TAG, "onLoadNextPage: jx");

                editCustomInfos = new ArrayList<QueryCustom.DataBean>();
                mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), i);
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (editCustomInfos.size() % 10 != 0)) {
                //the end
                Log.d(TAG, "onLoadNextPage:  !-9 ");
                mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                RecyclerViewStateUtils.setFooterViewState(getActivity(),
                        mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), i);
        }
    };

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: ");
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);

        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);

        measurementLayoutHeight();
    }


    @Override
    public int getUserID() {
        return
                mySetting.getInt("mId", 0);
    }

    @Override
    public String getCode() {
        return ed_1.getText().toString();
    }

    @Override
    public String getName() {
        return ed_2.getText().toString();
    }

    @Override
    public String getBusinessman() {
        return ed_3.getText().toString();
    }


    @Override
    public void loadCCIData(QueryCustom queryCustom) {

        mProgressDialog.cancel();
        for (QueryCustom.DataBean pi : queryCustom.getData()) {
            editCustomInfos.add(pi);
            editCustoms.add(pi);
        }
        setEditCustomInfoAdapter();
    }

    @Override
    public void hideCCIData(Throwable th) {

        mProgressDialog.cancel();
        throwable = th;
        ToastUtil.showToast(getContext(), th.getMessage());

    }

    @Override
    public void loadCTIData(CustomType customType) {
        mProgressDialog.cancel();
        for (CustomType.DataBean mt : customType.getData()
                ) {
            customTypes.add(mt);
            Log.d(TAG, "customTypes: "+mt.getName());
        }
        mPresenter.queryCopayTypeInfo(pageSize);
    }

    @Override
    public void hideCTIData(Throwable th) {
        mProgressDialog.cancel();
        throwable = th;
        RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        ToastUtil.showToast(getActivity(), th.getMessage());
    }

    @Override
    public void loadCpTIData(CustomType customType) {
        for (CustomType.DataBean mt : customType.getData()
                ) {
            copayTypes.add(mt);
            Log.d(TAG, "copayTypes: "+mt.getName());
        }
        mPresenter.queryMoneyTypeInfo(pageSize);
    }

    @Override
    public void hideCpTIData(Throwable th) {
        mProgressDialog.cancel();
        throwable = th;
        RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        ToastUtil.showToast(getActivity(), th.getMessage());
    }

    @Override
    public void loadMTIData(CustomType customType) {

        for (CustomType.DataBean mt : customType.getData()
                ) {
            moneyTypes.add(mt);
            Log.d(TAG, "moneyTypes: "+mt.getName());
        }
        if (editCustomInfoAdapter == null) {
            editCustomInfos = new ArrayList<QueryCustom.DataBean>();
            editCustoms = new ArrayList<QueryCustom.DataBean>();
            mPresenter.queryCocustomInfos(getCode(), getName(), getBusinessman(),getUserID(), pageSize);
        } else {
//            Log.d(TAG, "onClick: jg" + queryCondition.getStartDate());
            editCustomInfoAdapter.deleteItems(editCustomInfos);
            mRecyclerView.removeAllViews();
            editCustoms.clear();
            throwable = null;
            i = 0;
            editCustomInfos.clear();
            onRefresh();
        }
    }

    @Override
    public void hideMTIData(Throwable th) {
        mProgressDialog.cancel();
        throwable = th;
        RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        ToastUtil.showToast(getActivity(), th.getMessage());
    }

    @Override
    public void deleteCCIData(InsertStatus insertStatus) {
        mProgressDialog.cancel();
//        onRefresh();
        editCustomInfoAdapter.deleteItems(editCustomInfos);
        mRecyclerView.removeAllViews();
    }

    @Override
    public void failCCIData(Throwable th) {
        mProgressDialog.cancel();
        throwable = th;
        ToastUtil.showToast(getActivity(), th.getMessage());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                createProgressDialog(getResources().getString(R.string.querying));
                mPresenter.queryCocustomTypeInfo(pageSize);
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected EditCustomInfoPresenter loadPresenter() {
        return new EditCustomInfoPresenter();
    }

    @Override
    public void initSRView(View view) {
        super.initSRView(view);
        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);


        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }


    /**
     * 按钮点击事件需要的方法
     */
    public void buttonSetOnclick(ButtonInterface buttonInterface) {
        this.buttonInterface = buttonInterface;
    }

    /**
     * 按钮点击事件对应的接口
     */
    public interface ButtonInterface {
        void onclick(View view, int position, QueryCustom.DataBean queryCustom
                , ArrayList<CustomConditon> customConditons, ArrayList<CustomType.DataBean> customTypes,
                     ArrayList<CustomType.DataBean> moneyTypes,
                     ArrayList<CustomType.DataBean> copayTypes);

        void modify(View view, int position, QueryCustom.DataBean queryCustom,
                    ArrayList<CustomConditon> customConditons,
                    ArrayList<CustomType.DataBean> customTypes,
                    ArrayList<CustomType.DataBean> moneyTypes,
                    ArrayList<CustomType.DataBean> copayTypes,
                    SortedList<QueryCustom.DataBean> mSortedList
        );
    }

}
